package com.it.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.it.entity.Address;
import com.it.mapper.AddressMapper;
import com.it.service.AddressService;
import com.it.util.ItdragonUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Resource
    private ItdragonUtils itdragonUtils;
    @Resource
    private AddressMapper addressMapper;

    @Override
    public Page<Address> selectPage(Address address, int page, int limit) {
        EntityWrapper<Address> searchInfo = new EntityWrapper<>();
        Page<Address> pageInfo = new Page<>(page, limit);
        if (ItdragonUtils.stringIsNotBlack(address.getUserId())) {
            searchInfo.eq("userId", address.getUserId());
        }
        List<Address> resultList = addressMapper.selectPage(pageInfo, searchInfo);
        if (!resultList.isEmpty()) {
            pageInfo.setRecords(resultList);
        }
        return pageInfo;
    }

    @Override
    public boolean insert(Address address) {
        if (!ItdragonUtils.stringIsNotBlack(address.getIsDefault())) {
            address.setIsDefault("0");
        } else {
            //将该用户的默认地址改为非默认地址
            EntityWrapper<Address> wrapper = new EntityWrapper<>();
            wrapper.eq("userId", address.getUserId());
            wrapper.eq("isDefault", "1");
            Address address1 = new Address();
            address1.setIsDefault("0");
            addressMapper.update(address1, wrapper);
        }
        Integer insert = addressMapper.insert(address);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean delById(String id) {
        Integer delete = addressMapper.deleteById(id);
        if (delete > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean edit(Address address) {
        address.setIsDefault("1");
        //将该用户的默认地址改为非默认地址
        EntityWrapper<Address> wrapper = new EntityWrapper<>();
        wrapper.eq("userId", itdragonUtils.getSessionUser().getId());
        wrapper.eq("isDefault", "1");
        Address address1 = new Address();
        address1.setIsDefault("0");
        addressMapper.update(address1, wrapper);
        Integer update = addressMapper.updateById(address);
        if (update > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Address getAddress(String userId) {
        Address address = new Address();
        address.setUserId(userId);
        address.setIsDefault("1");
        Address one = addressMapper.selectOne(address);
        return one;
    }
}
